/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package accountmanager;

import java.io.File;
import java.util.HashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author jonesb
 */
public class ConfigurationManager implements IConfigurationManager {

    HashMap<String, String> allConfigs;

    public ConfigurationManager() {
        allConfigs = new HashMap<String, String>();
    }

    public HashMap<String, String> read(String fileName) throws Exception {
        // do some boilerplate stuff to read our XML.
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        DocumentBuilder db = dbf.newDocumentBuilder();


        // get access to the file passed in.
        File xmlFile = new File("config", fileName);

        // tell the DocumentBuilder to parse the file.
        Document doc = db.parse(xmlFile);

        // I have my starting point, so start recursing.
        readProperties(doc);

        return allConfigs;

    }

    /**
     * This is a recursive method that reads properties from an XML file.
     * @param doc
     */
    private void readProperties(Node node) {
        // if I don't have children, I am the base case.
        if (!node.hasChildNodes()) {
            // the value is simply the node value of the current node.
            String value = node.getNodeValue();
            // to get the key, we have to get the name of the parent node (the enclosing element).
            String key = node.getParentNode().getNodeName();

            //ok, now add them to the HashMap.
            allConfigs.put(key, value);
        } else {
            // we must be in a node that has children.  Recurse.
            NodeList childNodes = node.getChildNodes();

            // iterate over all children.
            for (int i = 0; i < childNodes.getLength(); i++)
            {
                // get this child.
                Node childNode = childNodes.item(i);
                
                // recurse.
                readProperties(childNode);
            }

        }
    }

}
